use super::Data;
use std::collections::HashMap;

/// 更新Map
pub(super) fn update_map(name: &str, val: String, map: &mut HashMap<String, Data>) {
    let fields = name.split(".").collect::<Vec<_>>();
    let first = fields[0];
    let second = fields[1];
    let third = fields[2];
    let index = second.parse::<usize>().unwrap_or_default();
    let list = map
        .entry(first.to_string())
        .and_modify(|data| {
            let list = data.get_list().unwrap();
            let map = list.get(index);
            if let Some(inner_data) = map {
                let mut map = inner_data.get_map().unwrap();
                let value = Data::from(val.clone());
                map.insert(third.to_string(), value);
                let value = Data::Object(map);
                data.update_list(index, &value);
            } else {
                let mut map = HashMap::new();
                let value = Data::from(val.clone());
                map.insert(third.to_string(), value);
                let value = Data::Object(map);
                data.add_list(&value);
            }
        })
        .or_insert(Data::from_vec(&[]));
    if list.is_empty_list() {
        let value = Data::from(val);
        let mut map = HashMap::new();
        map.insert(third.to_string(), value);
        let data = Data::Object(map);
        list.add_list(&data);
    }
}
